<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Item extends Model
{

    protected $fillable = ['name', 'describe', 'type', 'user_id', 'p_catalog_id', 'catalog_id', 'province_id', 'city_id', 'district_id', 'place', 'wanted_fee', 'find_time', 'lost_time'];

    public static $_typeName = ['find' => '捡到', 'lost' => '丢失'];

    /**
     * 发布的用户
     */
    public function user()
    {
        return $this->belongsTo('App\User', 'user_id', 'id')->withTrashed();
    }

    /**
     * 顶级分类
     */
    public function p_catalog()
    {
        return $this->belongsTo('App\Models\Catalog', 'p_catalog_id', 'id');
    }

    /**
     * 二级分类
     */
    public function catalog()
    {
        return $this->belongsTo('App\Models\Catalog', 'catalog_id', 'id');
    }

    /**
     * 省
     */
    public function province()
    {
        return $this->belongsTo('App\Models\Area', 'province_id', 'id');
    }

    /**
     * 市
     */
    public function city()
    {
        return $this->belongsTo('App\Models\Area', 'city_id', 'id');
    }

    /**
     * 区
     */
    public function district()
    {
        return $this->belongsTo('App\Models\Area', 'district_id', 'id');
    }

    /**
     * 匹配的物品
     */
    public function match()
    {
        return $this->hasOne('App\Models\Match', $this->type . '_item_id', 'id');
    }


    /**
     * 类型名称
     */
    public function typeName()
    {
        if (isset(static::$_typeName[$this->type])) {
            return static::$_typeName[$this->type];
        }
        return $this->type;
    }

    /**
     * 丢失/找到时间
     */
    public function findLostTime()
    {
        return $this->type == 'lost' ? $this->lost_time : $this->find_time;
    }

    /**
     * 详细地址
     */
    public function address()
    {
        return $this->province->name . $this->city->name . $this->district->name . $this->place;
    }

    public function status()
    {
        $matchStr = '未匹配';
        $confimStr = '未确认';
        if ($match = $this->match) {
            $matchStr = '已匹配';
            if ($match->confirm) {
                $confimStr = '已确认';
            }
        }
        return $matchStr . '/' . $confimStr;
    }

    /**
     * 获取匹配的物品
     */
    public function matchItem()
    {
        if ($match = $this->match) {
            $type_id = $this->type == 'lost' ? 'find_item_id' : 'lost_item_id';
            return $this->find($match->$type_id);
        }
        return null;
    }

    /**
     *
     */
    public function images()
    {
        return $this->hasMany('App\Models\ItemImage', 'item_id', 'id');
    }
}
